'use strict';

const fse = require('fs-extra')
const path = require('path')
const Controller = require('egg').Controller;

class ApiController extends Controller {
  async login() {
    const { ctx, app } = this;
    const token = app.jwt.sign({
      username: ctx.request.body.username
    }, app.config.jwt.secret);
    ctx.body = {             // 返回给前端
      token: token
    };
    ctx.status = 200;           // 状态码 200
  }

  async profile() {
    const { ctx } = this;
    ctx.body = {
      ...ctx.state.user
    }
  }

  async getFile() {
    const {ctx} = this;
    ctx.body = {
      // tpl: fse.readFileSync(path.join(app.baseDir, '/files/', ctx.request.query.file)).toString()
      tpl: fse.readFileSync(ctx.request.query.file).toString()
    }
  }

  async putFile() {
    const {ctx} = this;
    fse.outputFileSync(ctx.request.body.file, ctx.request.body.tpl)
    ctx.body = {}
  }

  async tmpFile() {
    let fileName = 'tmp/index.html'
    const {ctx, app} = this;
    let filePath = path.join(app.baseDir, '/app/view/' + fileName)
    fse.ensureFileSync(filePath)
    fse.outputFileSync(filePath, ctx.request.body.html)
    ctx.body = {}
  }

  async listFile() {
    const {ctx, service} = this;
    let filePath = ctx.request.query.folder;

   // console.log(filePath)
    let fileDirs = await service.file.fileDisplay(decodeURI(decodeURI(filePath)));

    ctx.body = {
      data: {
        dirs: fileDirs,
        filePath,
        user: ctx.state.user
      },
    }
  }

  async getFileStatus() {
    const {ctx, service} = this;
    let filePath = ctx.request.query.filepath.trim()
    let status = await service.file.stat(filePath);
    ctx.body = {
      data: status,
    }
  }
}

module.exports = ApiController;
